<?php
/**
 * Created by PhpStorm.
 * User: 69548
 * Date: 2018/7/24
 * Time: 10:32
 */

namespace app\api\controller;

use app\common\controller\Api;
use app\wap\controller\Kbxcoupon;
use app\wap\controller\Notify;
use app\admin\controller\Exchange;
use think\Db;
use think\db\Expression;
use think\Exception;
use think\log;

class Crontab extends Api
{
    private $domain = '';
    private $notice_email = '';

    public function _initialize()
    {
        Log::init([
            'type'  =>  'File',
            'path'  =>  APP_PATH.'logs/'
        ]);
        $this->domain = config('kbx_pro_url');
        $this->notice_email = config('SUPPORT_NOTICE_EMAIL');
    }

    //更新过期订单
    public function order(){
        $newtime=time()-1800;
        $where['order_status']=1;
        $data['order_status']=7;
        $order=Db::name('order')->where($where)->where('creattime','elt',$newtime)->select();
        foreach ($order as $key=>$value){
            if (!empty($value['cost_ticket_id'])){
                if ($value['coupon_type']=='KBX'){
                    $Kbxcoupon=  new Kbxcoupon();
                    $Kbxcoupon->refundCashCoupon($value['member_id'],$value['cost_ticket_id'],$value['order_no']);
                }else{
                    db('coupondetails')->where('id',$value['cost_ticket_id'])->update(['usestatus'=>0]);
                }
            }
            Db::name('order')->where($where)->where('order_id',$value['order_id'])->update($data);
        }
    }

    //更新汇率
    public function exchangeRate(){
        $Exchange = new Exchange();
        $rateArr = $Exchange->get_rate();
        $time = time();
        $nameArr = [
            'USD'=>"美元",
            'CAD'=>"加元",
            'NZD'=>"新西兰元",
            'JPY'=>"日元",
        ];
        if(!empty($rateArr['CNY'])){
            $USD_rate = $rateArr['CNY'];//美元转人民币
            unset($rateArr['CNY']);
            if(!empty($rateArr)){
                foreach ($rateArr as $key=>$value) {
                    $params = [];
                    $params['updatetime'] = $time;

                    if($key=='USD'){
                        $params['exchange_rate'] = number_format($USD_rate,4);
                    }else{
                        $params['exchange_rate'] = number_format($USD_rate/$value,4);
                    }

                    $rateRes = db('exchange')->where('currency_code',$key)->find();
                    if(!empty($rateRes)){//存在时更新
                        $res = db('exchange')->where('currency_code',$key)->update($params);
                    }else{//不存在时创建
                        $params['name'] = isset($nameArr[$key]) ? $nameArr[$key]."转人民币" : $key."转人民币";
                        $params['creation_time'] = $time;
                        $params['currency_code'] = $key;
                        $params['admin_id'] = 1;
                        $res = db('exchange')->insert($params);
                    }

                    if(!$res){
                        $log[] = [
                            '汇率更新脚本运行失败' => ['params'=>$params,'res'=>$res]
                        ];
                        Log::record($log);
                    }
                }
            }
        }else{
            $log[] = [
                '汇率更新脚本运行失败' => "缺少美元转人民币汇率"
            ];
            Log::record($log);
        }
        die;
    }

    //发送提醒二维码过期提醒
    public function noticeExpiredQrcode()
    {
        $notice_expire_time = date('Y-m-d',strtotime('+1 day'));
        $res = db('grouptour_qrcode')
            ->where(['expire_time'=>['elt',$notice_expire_time]])
            ->field('id,grouptour_id,title,notice_email')->select();
        if(empty($res)){
            trace('qrcode tips : 今日没有群二维码过期');
            return json_encode(['code'=>200,'msg'=>'今日没有群二维码过期']);
        }
        $subject = '【群二维码过期提醒】';
        $domain = $this->domain."admin/grouptoursline/index";
        foreach ($res as $value){
            $content = '<p>拼游产品ID为【'.$value['grouptour_id'].'】的【'.$value['title'].'】邀请码今日到期<br>请前往定制后台更新群邀请码！<br>【产品&定制 > 拼团产品列表】<br><a href="'.$domain.'">'.$domain.'</a></p>';
            if(empty($value['notice_email'])){
                continue;
            }
            $email_res = (new Notify())->kbxemailcode($subject,$content,$value['notice_email']);
            trace('qrcode tips : 拼游产品ID为【'.$value['grouptour_id'].'】的【'.$value['title'].'】群二维码过期提醒邮件已发送。'.json_encode($email_res));
        }
        return json_encode(['code'=>200,'msg'=>'群二维码过期提醒邮件已发送']);
    }

    //更新商品的价格 脚本
    public function updateGoodsMinAndMaxPrice()
    {
        ignore_user_abort();//关闭浏览器仍然运行
        set_time_limit(0);//程序运行不停止

        trace(date('Y-m-d H:i:s').':更新商品的最大和最小价格开始');
        //1 获取上架的所有商品
        $hasCodeGoogs = db('goods g')
            ->join('product p','p.item_num=g.goods_tcode','left')
            ->field('g.goods_id,p.id as product_id,p.new_price_flag,p.base_price_mode,g.goods_tcode')
            ->where([
                'g.goods_status'=>1,
                'goods_tcode'=>['exp',new Expression('is not null and goods_tcode!=""')]
            ])
            ->select();
        $noCodeGoods = db('goods g')
            ->field('g.goods_id, 0 as product_id,0 as new_price_flag,0 as base_price_mode')
            ->where([
                'g.goods_status'=>1,
                'goods_tcode'=>['exp',new Expression('is null or goods_tcode=""')]
            ])
            ->select();
        //合并所有商品
        $list = array_merge($hasCodeGoogs,$noCodeGoods);

        //2 获取上架商品的价格区间
        if(empty($list)){
            trace('暂无需要更新的商品数据');
            trace(date('Y-m-d H:i:s').':更新商品的最大和最小价格结束');
            return json_encode(['code'=>200,'msg'=>'暂无需要更新的商品数据']);
        }
        //开启事务
        Db::startTrans();
        try{
            //统计总数
             $num = 0;
            foreach ($list as $key=>$value){

                if(!empty($value['base_price_mode']) && $value['base_price_mode']==1){
                    $price_data = db("product_base_dailyprice")->field('min(price) as min_price,max(price) as max_price')
                        ->where(['product_id'=>$value['product_id']])
                        ->find();
                }elseif(!empty($value['new_price_flag']) && $value['new_price_flag']==1){
                    $price_data = db("product_dailyprice")->field('min(price) as min_price,max(price) as max_price')
                        ->where(['product_id'=>$value['product_id']])
                        ->find();
                }else{
                    $price_data = db("personday")->field('min(person_price) as min_price,max(person_price) as max_price')
                        ->where(['goods_id'=>$value['goods_id']])
                        ->find();
                }
                if(empty($price_data)) continue;//未查询到价格直接跳过
                //3 更新商品价格的最大和最小值
                //开始更新数据
                if(!empty($value['base_price_mode']) && $value['base_price_mode']==1){
                    db('product')->where('id',$value['product_id'])->update([
                        'min_price'=>$price_data['min_price']??0,
                        'max_price'=>$price_data['max_price']??0,
                    ]);
                    trace('更新商品【'.$value['goods_id'].'】关联产品【'.$value['product_id'].'】的数据成功');
                }elseif(!empty($value['new_price_flag']) && $value['new_price_flag']==1){
                    db('product')->where('id',$value['product_id'])->update([
                        'min_price'=>$price_data['min_price']??0,
                        'max_price'=>$price_data['max_price']??0,
                    ]);
                    trace('更新商品【'.$value['goods_id'].'】关联产品【'.$value['product_id'].'】的数据成功');
                }
                db('goods')->where('goods_id',$value['goods_id'])->update([
                    'min_price'=>$price_data['min_price']??0,
                    'max_price'=>$price_data['max_price']??0,
                ]);
                trace('更新商品ID【'.$value['goods_id'].'】的数据成功');
                $num ++ ;
            }
            Db::commit();
            trace('共计更新商品数量：'.$num.'个');
            trace(date('Y-m-d H:i:s').':更新商品的最大和最小价格结束');
            return json_encode(['code'=>200,'msg'=>'更新成功,共计更新商品数量：'.$num.'个']);
        }catch (Exception $e){
            Db::rollback();
            trace('更新失败，失败原因：'.$e->getMessage());
            trace(date('Y-m-d H:i:s').':更新商品的最大和最小价格结束');
            return json_encode(['code'=>400,'msg'=>'更新失败，失败原因：'.$e->getMessage()]);
        }
    }

}